package com.mars.foodserver.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.mars.foodserver.entity.SysUser;
import com.mars.foodserver.entity.User;
import com.mars.foodserver.exception.WorkException;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;

/**
 * @author wq
 * @version 1.0
 * @date 2021/06/04 16:16
 */
@Slf4j
public class JwtUtil {

    /**
     * jwt 密钥
     */
    private static final String SECRET = "d6f7c121-d2e9-436d-8d9c-952de82b38aa";


    /**
     * 生成前台用户令牌
     *
     * @param user       用户
     * @param expireTime 过期时间
     * @return 令牌
     */
    public static String createUserToken(User user, long expireTime) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    .withClaim("userId", user.getId())
                    .withExpiresAt(new Date(expireTime))
                    .sign(algorithm);
        } catch (Exception e) {
            log.error("error：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 生成后台用户令牌
     *
     * @param sysUser    用户
     * @param expireTime 过期时间
     * @return 令牌
     */
    public static String createSysUserToken(SysUser sysUser, long expireTime) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    .withClaim("sysUserId", sysUser.getId())
                    .withClaim("nickname", sysUser.getNickname())
                    .withClaim("roleId", sysUser.getRoleId())
                    .withExpiresAt(new Date(expireTime))
                    .sign(algorithm);
        } catch (Exception e) {
            log.error("error：{}", e.getMessage());
            return null;
        }
    }


    /**
     * 根据令牌获取前台用户ID
     *
     * @param token token
     * @return 用户ID
     */
    public static String getUserId(String token) {
        try {
            Map<String, Claim> claims = JWT.decode(token).getClaims();
            if (!claims.get("userId").isNull()) {
                return claims.get("userId").asInt().toString();
            }
        } catch (JWTDecodeException e) {
            throw new RuntimeException("获取系统用户ID异常" + e.getMessage());
        }
        return null;
    }

    /**
     * 根据令牌获取后台用户ID
     *
     * @param token token
     * @return 用户ID
     */
    public static String getSysUserId(String token) {
        try {
            Map<String, Claim> claims = JWT.decode(token).getClaims();
            if (!claims.get("sysUserId").isNull()) {
                return claims.get("sysUserId").asInt().toString();
            }
        } catch (JWTDecodeException e) {
            throw new RuntimeException("获取系统用户ID异常" + e.getMessage());
        }
        return null;
    }

    /**
     * 校验token
     *
     * @param token 令牌
     * @return 是否成功
     */
    public static boolean checkToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception) {
            return false;
        }
    }


}
